import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { flyIn } from '../../../../animations/fly-in';
import {HttpRequest} from "../../../../service/httpRequest";
import { PageModel } from "../../../../model/page-model";

declare let $:any;
@Component({
  selector: 'app-assin-device',
  templateUrl: './assin-device.component.html',
  styleUrls: ['./assin-device.component.css'],
  animations: [
    flyIn
  ]
})
export class AssinDeviceComponent implements OnInit {

  keyword:string = '';
  data = [];
  pageModel = new PageModel();
  model = {account_id:'',page:1,size:this.pageModel.itemsPerPage,name:''};
  constructor(private httpRequest:HttpRequest,private activeRoute:ActivatedRoute) { }

  ngOnInit() {

    this.activeRoute.params.subscribe(params => {
      this.model.account_id = params['accountId'];
      this.getData();
    });
  }

  getData(){
    this.httpRequest.sendGet('devices/list',this.model).subscribe(res=>{
      this.data = res.result.aaData;
      this.pageModel.setPage({'iTotalRecords':res.result.iTotalRecords});
    },err=>console.log(err));
  }

  search(){
    this.model.name = this.keyword;
    this.getData();
  }

  save(){
    let device_ids = '';
    let dids = $('input[type=checkbox]:checked');
    for (let i = 0;i< dids.length;i++) {
      device_ids += $(dids[i]).val() +';';
    }
    let pg_ids = [];
    for(let i = 0 ; i<this.data.length;i++){
      pg_ids.push(this.data[i].id)
    }


    this.httpRequest.sendPost('account/devicerelate',{
      account_id:this.model.account_id,
      device_ids:device_ids.substring(0,device_ids.length-1),
      pg_ids:pg_ids.join(';')
    }).subscribe(res => {
      alert("设备分配完成！");
      this.getData();
    },err => {alert('设备分配失败!');console.log(err)});
  }
}
